<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Omi</title>
    <!-- Include Firebase SDKs -->
    <script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-auth-compat.js"></script>
    <!-- Include FirebaseUI for easy login UI, or use custom Firebase auth calls -->
    <script src="https://www.gstatic.com/firebasejs/ui/6.0.1/firebase-ui-auth.js"></script>
    <link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/6.0.1/firebase-ui-auth.css" />
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            margin: 0;
            background-color: #f7f7f7;
            color: #333;
        }

        .oauth-card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 480px;
            margin: 20px;
            overflow: hidden;
        }

        .card-header {
            padding: 16px 24px;
            border-bottom: 1px solid #eee;
            font-size: 16px;
            font-weight: 500;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-header .omi-logo {
            font-weight: bold;
        }

        .card-content {
            padding: 32px 24px;
            text-align: center;
        }

        .app-info img {
            width: 64px;
            height: 64px;
            border-radius: 12px;
            margin-bottom: 16px;
            object-fit: cover;
            border: 1px solid #eee;
        }

        .app-info h1 {
            font-size: 24px;
            font-weight: 600;
            margin-top: 0;
            margin-bottom: 8px;
        }

        .app-info p {
            font-size: 16px;
            color: #555;
            margin-bottom: 24px;
        }

        .permissions-title {
            font-size: 14px;
            font-weight: 500;
            color: #333;
            text-align: left;
            margin-bottom: 8px;
            padding-left: 10px;
            /* Align with items */
        }

        .permissions-list {
            list-style: none;
            padding: 0;
            margin: 0 0 24px 0;
            text-align: left;
        }

        .permissions-list li {
            font-size: 14px;
            color: #555;
            padding: 8px 10px;
            border-top: 1px solid #f0f0f0;
            display: flex;
            align-items: center;
        }

        .permissions-list li:first-child {
            border-top: none;
        }

        .permissions-list li .perm-icon {
            margin-right: 8px;
            font-size: 16px;
        }

        #firebaseui-auth-container {
            margin-top: 20px;
        }

        .error {
            color: red;
            margin-top: 15px;
            font-size: 14px;
        }

        .card-footer {
            padding: 16px 24px;
            background-color: #f9f9f9;
            border-top: 1px solid #eee;
            font-size: 12px;
            color: #777;
            text-align: left;
        }

        .card-footer a {
            color: #555;
            text-decoration: underline;
        }

        /* FirebaseUI overrides for a cleaner look if needed */
        .firebaseui-card-header {
            display: none !important;
        }

        /* Hide FirebaseUI's own header */
        .firebaseui-card-content {
            padding: 0 !important;
            box-shadow: none !important;
        }

        .firebaseui-list-item {
            margin: 10px 0 !important;
        }

        .firebaseui-idp-button {
            max-width: 100% !important;
        }
    </style>
</head>

<body>
    <div class="oauth-card">
        <div class="card-header">
            <span class="omi-logo">Omi</span>
            <!-- Optionally, display user info if available: <span class="user-info">username@example.com</span> -->
        </div>
        <div class="card-content">
            <div class="app-info">
                {% if app_image %}
                <img src="{{ app_image }}" alt="{{ app_name }} logo">
                {% else %}
                <img src="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🧩</text></svg>"
                    alt="{{ app_name }} logo"> <!-- Placeholder icon -->
                {% endif %}
                <h1>{{ app_name }}</h1>
                <p>wants to access your Omi account.</p>
            </div>

            {% if permissions %}
            <div class="permissions-section">
                <p class="permissions-title"><strong>{{ app_name }}</strong> wants to:</p>
                <ul class="permissions-list">
                    {% for perm in permissions %}
                    <li><span class="perm-icon">{{ perm.icon }}</span> {{ perm.text }}</li>
                    {% endfor %}
                </ul>
            </div>
            {% endif %}

            <div id="firebaseui-auth-container"></div>
            <div id="loader" style="display:none;">Loading...</div>
            <div id="error-message" class="error"></div>
        </div>
        <div class="card-footer">
            Make sure you trust <strong>{{ app_name }}</strong>.
            By authorizing, you allow this app to use your data in accordance with Omi's <a
                href="https://www.omi.me/pages/privacy">Terms of
                Service</a> and <a href="https://www.omi.me/pages/privacy">Privacy Policy</a>.
        </div>
    </div>

    <script>
        // These values are passed from the backend template rendering
        const appId = "{{ app_id }}";
        const state = "{{ state }}";

        // Firebase configuration
        const firebaseConfig = {
            apiKey: "{{ firebase_api_key }}",
            authDomain: "{{ firebase_auth_domain }}",
            projectId: "{{ firebase_project_id }}"
        };

        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);

        function isAppleDevice() {
            return /Mac|iPod|iPhone|iPad/.test(navigator.platform);
        }

        let signInOptions = [
            firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        ];

        if (isAppleDevice()) {
            signInOptions.push('apple.com');
        }

        const uiConfig = {
            signInFlow: 'popup', // Use popup flow instead of redirect
            signInSuccessUrl: null, // We will handle redirect manually
            signInOptions: signInOptions,
            callbacks: {
                signInSuccessWithAuthResult: function (authResult, redirectUrlParam) {
                    document.getElementById('loader').style.display = 'block';
                    document.getElementById('firebaseui-auth-container').style.display = 'none';
                    document.getElementById('error-message').textContent = '';

                    authResult.user.getIdToken().then(function (idToken) {
                        // Send ID token to backend /oauth/token
                        const formData = new FormData();
                        formData.append('firebase_id_token', idToken);
                        formData.append('app_id', appId);
                        if (state) {
                            formData.append('state', state);
                        }

                        fetch('/v1/oauth/token', {
                            method: 'POST',
                            body: formData
                        })
                            .then(response => {
                                if (!response.ok) {
                                    return response.json().then(err => {throw new Error(err.detail || 'Authentication failed');});
                                }
                                return response.json();
                            })
                            .then(data => {
                                let finalRedirectUrl = data.redirect_url + "?uid=" + data.uid;
                                if (data.state) {
                                    finalRedirectUrl += "&state=" + data.state;
                                }
                                window.location.href = finalRedirectUrl;
                            })
                            .catch(error => {
                                console.error('Error during token exchange:', error);
                                document.getElementById('error-message').textContent = 'Error: ' + error.message;
                                document.getElementById('loader').style.display = 'none';
                                document.getElementById('firebaseui-auth-container').style.display = 'block'; // Show login again
                            });
                    }).catch(function (error) {
                        console.error('Error getting ID token:', error);
                        document.getElementById('error-message').textContent = 'Error: Could not get user token.';
                        document.getElementById('loader').style.display = 'none';
                        document.getElementById('firebaseui-auth-container').style.display = 'block';
                    });

                    return false;
                },
                signInFailure: function (error) {
                    console.error('FirebaseUI signInFailure error:', error);
                    document.getElementById('error-message').textContent = 'Sign-in failed. Code: ' + error.code + (error.message ? ' Message: ' + error.message : '');
                    document.getElementById('loader').style.display = 'none';
                    document.getElementById('firebaseui-auth-container').style.display = 'block'; // Show login again
                },
                uiShown: function () {
                    console.log("FirebaseUI uiShown: UI has been rendered.");
                    document.getElementById('loader').style.display = 'none';
                }
            }
        };

        // Initialize the FirebaseUI Widget using Firebase.
        const ui = new firebaseui.auth.AuthUI(firebase.auth());
        // The start method will wait until the DOM is loaded.
        ui.start('#firebaseui-auth-container', uiConfig);

    </script>
</body>

</html>
